{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1. 创建DataFrame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     Name  Age      City\n",
      "0     Tom   20  New York\n",
      "1    Nick   21    London\n",
      "2   Julia   19     Paris\n",
      "3  Sophia   18     Tokyo\n"
     ]
    }
   ],
   "source": [
    "'''从字典创建：'''\n",
    "import pandas as pd\n",
    "data = {\n",
    "    'Name': ['Tom', 'Nick', 'Julia', 'Sophia'],\n",
    "    'Age': [20, 21, 19, 18],\n",
    "    'City': ['New York', 'London', 'Paris', 'Tokyo']\n",
    "}\n",
    "\n",
    "df = pd.DataFrame(data)\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     Name  Age      City Country\n",
      "0     Tom   20  New York     NaN\n",
      "1    Nick   21    London     NaN\n",
      "2   Julia   19     Paris     NaN\n",
      "3  Sophia   18     Tokyo     NaN\n"
     ]
    }
   ],
   "source": [
    "'''指定列索引：'''\n",
    "df_with_col_index = pd.DataFrame(data, columns=['Name', 'Age', 'City', 'Country'])\n",
    "print(df_with_col_index)  # 注意'Country'列会有NaN值，因为原始数据中没有提供"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 2. 查看数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 4 entries, 0 to 3\n",
      "Data columns (total 3 columns):\n",
      " #   Column  Non-Null Count  Dtype \n",
      "---  ------  --------------  ----- \n",
      " 0   Name    4 non-null      object\n",
      " 1   Age     4 non-null      int64 \n",
      " 2   City    4 non-null      object\n",
      "dtypes: int64(1), object(2)\n",
      "memory usage: 224.0+ bytes\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "#基本信息：\n",
    "print(df.info())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     Name  Age      City\n",
      "0     Tom   20  New York\n",
      "1    Nick   21    London\n",
      "2   Julia   19     Paris\n",
      "3  Sophia   18     Tokyo\n",
      "     Name  Age   City\n",
      "2   Julia   19  Paris\n",
      "3  Sophia   18  Tokyo\n"
     ]
    }
   ],
   "source": [
    "#前几行/后几行：\n",
    "print(df.head())  # 默认显示前5行\n",
    "print(df.tail(2))  # 显示最后3行"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3. 选择与筛选数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    20\n",
      "1    21\n",
      "2    19\n",
      "3    18\n",
      "Name: Age, dtype: int64\n"
     ]
    }
   ],
   "source": [
    "#通过列名选择列：\n",
    "print(df['Age'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     Name      City\n",
      "0     Tom  New York\n",
      "1    Nick    London\n",
      "2   Julia     Paris\n",
      "3  Sophia     Tokyo\n"
     ]
    }
   ],
   "source": [
    "#多列选择：\n",
    "print(df[['Name', 'City']])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Name  Age      City\n",
      "0   Tom   20  New York\n",
      "1  Nick   21    London\n"
     ]
    }
   ],
   "source": [
    "#布尔索引：\n",
    "print(df[df['Age'] > 19])  # 选择年龄大于19的行"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 4. 添加和删除列"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     Name  Age      City Country\n",
      "0     Tom   20  New York     USA\n",
      "1    Nick   21    London      UK\n",
      "2   Julia   19     Paris  France\n",
      "3  Sophia   18     Tokyo   Japan\n"
     ]
    }
   ],
   "source": [
    "#添加列：\n",
    "df['Country'] = ['USA', 'UK', 'France', 'Japan']\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     Name  Age      City\n",
      "0     Tom   20  New York\n",
      "1    Nick   21    London\n",
      "2   Julia   19     Paris\n",
      "3  Sophia   18     Tokyo\n"
     ]
    }
   ],
   "source": [
    "#删除列：\n",
    "\n",
    "df.drop('Country', axis=1, inplace=True)\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 5. 数据排序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     Name  Age      City\n",
      "3  Sophia   18     Tokyo\n",
      "2   Julia   19     Paris\n",
      "0     Tom   20  New York\n",
      "1    Nick   21    London\n"
     ]
    }
   ],
   "source": [
    "#按单列排序：\n",
    "\n",
    "print(df.sort_values(by='Age'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     Name  Age      City\n",
      "3  Sophia   18     Tokyo\n",
      "2   Julia   19     Paris\n",
      "0     Tom   20  New York\n",
      "1    Nick   21    London\n"
     ]
    }
   ],
   "source": [
    "#多列排序：\n",
    "\n",
    "print(df.sort_values(by=['Age', 'Name']))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 6. 数据清洗"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     Name  Age      City      NewColumn\n",
      "0     Tom   20  New York   Filled Value\n",
      "1    Nick   21    London     some value\n",
      "2   Julia   19     Paris   Filled Value\n",
      "3  Sophia   18     Tokyo  another value\n"
     ]
    }
   ],
   "source": [
    "#处理缺失值：\n",
    "import numpy as np\n",
    "\n",
    "df['NewColumn'] = [np.nan, 'some value', np.nan, 'another value']\n",
    "print(df.fillna('Filled Value'))  # 用特定值填充缺失值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     Name  Age    City      NewColumn\n",
      "1    Nick   21  London     some value\n",
      "3  Sophia   18   Tokyo  another value\n"
     ]
    }
   ],
   "source": [
    "#删除包含缺失值的行：\n",
    "\n",
    "print(df.dropna())  # 删除含有任何缺失值的行"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 7. 数据转换与重塑"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Name         object\n",
      "Age          object\n",
      "City         object\n",
      "NewColumn    object\n",
      "dtype: object\n"
     ]
    }
   ],
   "source": [
    "#更改列数据类型：\n",
    "\n",
    "df['Age'] = df['Age'].astype('str')\n",
    "print(df.dtypes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     Name Years      City      NewColumn\n",
      "0     Tom    20  New York            NaN\n",
      "1    Nick    21    London     some value\n",
      "2   Julia    19     Paris            NaN\n",
      "3  Sophia    18     Tokyo  another value\n"
     ]
    }
   ],
   "source": [
    "#重命名列名：\n",
    "\n",
    "df.rename(columns={'Age': 'Years'}, inplace=True)\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 8. 数据聚合与分组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "19.5\n"
     ]
    }
   ],
   "source": [
    "#基础聚合：\n",
    "\n",
    "print(df['Age'].mean())  # 平均年龄"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "City\n",
      "London      21.0\n",
      "New York    20.0\n",
      "Paris       19.0\n",
      "Tokyo       18.0\n",
      "Name: Age, dtype: float64\n"
     ]
    }
   ],
   "source": [
    "#分组操作：\n",
    "\n",
    "grouped = df.groupby('City')['Age'].mean()  # 只对'Age'列计算平均值\n",
    "print(grouped)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "           Age\n",
      "City          \n",
      "London    21.0\n",
      "New York  20.0\n",
      "Paris     19.0\n",
      "Tokyo     18.0\n"
     ]
    }
   ],
   "source": [
    "numeric_df = df.select_dtypes(include=[np.number])  # 仅选择数值类型列\n",
    "grouped_numeric = numeric_df.groupby(df['City']).mean()  # 根据'City'列分组并计算数值列的平均值\n",
    "print(grouped_numeric)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
